const express = require("express");
const router = express.Router();

const { timeTrans } = require("../../../utils");
const {
  getUsers,
  addUsers,
  updateUsers,
  deleteUsers,
} = require("../../../model/weixin/admin/users");

/* users增删改查 */

// 查找users
router.get("/", async function (req, res, next) {
  let data = await getUsers();
  res.send(data);
});

// 添加users
router.post("/add", (req, res, next) => {
  console.log("----------------users请求---------------", req.body);
  const users_id = Number(req.body.users_id);
  let { username, password, nickname } = req.body;
  let role = nickname === "管理员" ? 2 : 3;
  const ctime = timeTrans(req.body.ctime);
  // console.log(users_id, username, password, nickname, role, ctime);
  // return;
  addUsers([users_id, username, password, nickname, role, ctime])
    .then(() => {
      res.send({
        code: 200,
        msg: "添加用户成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "添加用户失败",
        err,
      });
    });
});

// 修改users
router.post("/update", (req, res, next) => {
  const users_id = Number(req.body.users_id);
  let { username, password, nickname } = req.body;
  let role = nickname === "管理员" ? 2 : 3;
  const utime = timeTrans(req.body.utime);
  // console.log(users_id, username, password, nickname, role, utime);
  // return;
  updateUsers([username, password, nickname, role, utime, users_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改用户成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "修改用户失败",
        err,
      });
    });
});

// 删除users
router.get("/delete", (req, res, next) => {
  const users_id = Number(req.query.users_id);
  deleteUsers([users_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "删除用户成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "删除用户失败",
      });
    });
});

module.exports = router;
